<template>
  <view class="container" v-if="goods.length">
    <view class="goods-list">

      <view class="goods-item" v-for="(item, index) in goods" :key="index">
        <!-- 商品详情 -->

        <view class="goods-detail dis-flex flex-dir-row">
          <view class="left">
            <image class="goods-image" :src="item.goods_image"></image>
          </view>
          <view class="right dis-flex flex-box flex-dir-column flex-x-around">
            <text class="twolist-hidden">{{ item.goods_name }}</text>
            <view class="twolist-hidden spec">{{ item.goods_spec }}</view>
            <text class="">￥{{ item.goods_price }}</text>
          </view>
        </view>

        <!-- 选择评价 -->

        <view class="score-row ">
          <u-rate :count="5" gutter="20" :min-count="1" active-color="#e70ea3" v-model="formData[index].score"></u-rate>

        </view>
        <view class="score-row dis-flex content-row is_anonymous">
          <text class="text">设为匿名</text>
          <u-switch class="switch"  active-value="1" inactive-value="0" active-color="#e70ea3" v-model="formData[index].is_anonymous"></u-switch>

        </view>

        <!-- 评价内容 -->

        <view class="dis-flex content-row">
          <textarea @input="contentInput" :data-index="index" maxlength="2000"
                    placeholder="请输入评价内容 (留空则不评价)" placeholderStyle="color:#ccc"></textarea>
        </view>

        <!-- 图片列表 -->

        <view class="image-list">
          <upload-file
              :auto-upload="false"
              :unique_id="index"
              ref="upload"
              :action="action"
              :max-size="maxSize"
              :max-count="maxCount"
              :limit-type="limitType"

              @success="handleFileUploadSuccess"
              @remove="handleFileUploadRemove"
              @error="handleError"
              @choose-ok="handleChooseOK"
          />
        </view>
      </view>
    </view>

    <view class="flow-fixed-footer b-f">
      <view class="flow-btn f-32">
        <view @tap.stop.prevent="submit">确认提交</view>
      </view>
    </view>
  </view>
</template>

<script>
import comment_api from "@/common/comment_api";
import uploadFile from "@/components/UploadFile.vue";
import constConfig from "const";

export default {
  components: {
    uploadFile
  },
  data() {
    return {
      action: constConfig.baseUrl + '/upload/image',
      maxSize: 2 * 1024 * 1024, // 可以设置不同的大小限制
      maxCount: 3, // 可以设置不同的数量限制
      limitType: ['png', 'jpg', 'jpeg'], // 支持的文件类型
      // 页面参数
      options: null,

      // 待评价商品列表
      goods: [],

      // 表单数据
      formData: [],
      imageCount: 0,
      uploadCount: 0,
      submitDisable: false,
      score: 0,
      image_list: []
    };
  }
  /**
   * 生命周期函数--监听页面加载
   */,
  onLoad: function (options) {
    this.options = options;
    this.getReady();
  },
  methods: {
    handleChooseOK(res) {
      let {fileList, index, unique_id} = res
      console.log('handleChooseOK', [fileList, index, unique_id])
      //this.formData[unique_id].image_list = fileList
      this.imageCount++;
    },
    handleError(data, index, lists, name) {
      this.$u.toast('文件上传失败')
      this.handleRemove(index, lists, name)
    },

    handleFileUploadSuccess({url, index, fileList, res, unique_id}) {
      console.log('文件上传成功:', fileList);
      if (res.code == 0) {
        this.formData[unique_id].image_list.push(res.data.full_url)
        console.log(this.formData[unique_id].image_list)
        this.setData({
          ['formData[' + unique_id + '].image_list']: this.formData[unique_id].image_list
        });
        this.uploadCount++;
      } else {
        this.$u.toast(res.msg)
        //移除文件
        this.$refs.upload.remove(index)

        this.formData[unique_id].image_list.splice(index, 1)
      }
    },
    handleFileUploadRemove({index, fileList, unique_id}) {
      // 更新状态或者做其他处理
      console.log('文件已被移除:', index);
      this.formData[unique_id].image_list.splice(index, 1)
      this.imageCount--;
      return true
    },
    /**
     * 获取待评价商品列表
     */
    getReady: function () {
      let that = this;
      comment_api.comment_ready({
        order_sn: that.options.order_sn
      }).then(res => {
        if (res.code !== 0) {
          that.$u.toast(res.msg);
          setTimeout(function () {
            uni.navigateBack();
          }, 2000)
          return;
        }
        that.setData({
          goods: res.data.goods,
          formData: that.initFormData(res.data.goods)
        });
      })

    },

    /**
     * 初始化form数据
     */
    initFormData: function (goodsList) {
      let data = [];
      goodsList.forEach(function (item) {
        data.push({
          goods_id: item.goods_id,
          order_goods_id: item.id,
          score: 0,
          is_anonymous: false,
          content: '',
          image_list: []
        });
      });
      return data;
    },


    /**
     * 输入评价内容
     */
    contentInput: function (e) {
      let index = e.currentTarget.dataset.index;
      this.setData({
        ['formData[' + index + '].content']: e.detail.value
      });
    },

    /**
     * 表单提交
     */
    async submit() {
      let that = this;
      let formData = that.formData; // 判断是否重复提交
      if (that.submitDisable === true) {
        return false;
      }
      uni.showLoading({
        title: '正在处理...',
        mask: true
      });

      //todo 多图上传被异步的问题，目前用了while 循环，但可能存在问题，需要优化


      let pollCount = 0; // 新增：用于记录轮询次数
      const maxPollAttempts = 60; // 设置最大轮询次数（例如60次，即最多等待60秒）
      console.log('imageCount', that.imageCount)
      // 遍历所有的upload组件并调用startUpload
      await this.$refs.upload.forEach(uploadComponent => {
        uploadComponent.startUpload();
      });
      // 等待所有图片上传完成
      while (that.imageCount > that.uploadCount) {
        await new Promise(resolve => setTimeout(resolve, 1000));
        pollCount++; // 每次轮询后增加计数器

        // 可选：在每次轮询时检查是否已经完成上传，提前退出
        if (that.imageCount === that.uploadCount || pollCount >= maxPollAttempts) {
          break;
        }
      }
      if (pollCount >= maxPollAttempts) {
        console.warn('达到最大轮询次数，可能有上传任务未完成');
        // 在这里可以添加一些额外的逻辑，比如提示用户上传可能失败了
      }
      console.log('uploadedCount', that.uploadCount)
      // 表单提交按钮设为禁用 (防止重复提交)
      that.submitDisable = true;
      //每个评价至少一个1分
      for (let i = 0; i < formData.length; i++) {
        if (formData[i].score <= 0) {
          uni.hideLoading();
          that.submitDisable = false;
          that.$u.toast('请选择第' + (1 + i) + '个商品的评价星星数');
          return false;
        }
      }

      // form提交执行函数
      let submit = (formData) => {
        comment_api.create({
          order_sn: that.options.order_sn,
          formData: JSON.stringify(formData)
        }).then(res => {
          that.$u.toast(res.msg);
          if (res.code !== 0) {
            return;
          }
          setTimeout(function () {
            uni.navigateBack();
          }, 2000)
        }).finally(function () {
          uni.hideLoading();
          that.submitDisable = false;
        })
      };

      submit(formData);
    },

  }
};
</script>
<style lang="scss" scoped>
@import 'form.scss';
</style>

